package org.dataframework.security.core.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiuCf
 * @Email: 1316640406@qq.com
 * @Date: 2021/7/3 12:50
 */
public class MysqlTableSelector implements TableSelector {
    private static final Logger logger = LoggerFactory.getLogger(MysqlTableSelector.class);

    public static final String DEF_TABLE_ALL_QUERY = "select table_name from information_schema.tables where table_schema = (select database())";
    public static final String DEF_COLUMN_BY_TABLE_QUERY = "select table_name, collation_name, data_type from information_schema.columns where table_schema = (select database()) and table_name = ?";
    private JdbcTemplate jdbcTemplate;

    public MysqlTableSelector() throws SQLException {
        jdbcTemplate = new DefaultMysqlJdbcTemplate();
    }

    @Override
    public List<Table> loadTables() {
        try {
            return jdbcTemplate.selectAll(MysqlTableSelector.DEF_TABLE_ALL_QUERY, Table.class, RowMappers.tableMapper());
        } catch (SQLException exception) {
            logger.error("数据库表查询出错===>{}", exception.getMessage());
        }
        return new ArrayList<>();
    }

    @Override
    public List<Column> loadColumnsByTable(String table) {
        try {
            return jdbcTemplate.selectAll(MysqlTableSelector.DEF_COLUMN_BY_TABLE_QUERY.replace("?", "'" + table + "'"), Column.class, RowMappers.columnMapper());
        } catch (SQLException exception) {
            logger.error("数据库表列信息查询出错===>{}", exception.getMessage());
        }
        return new ArrayList<>();
    }
}
